package com.xuecheng.search.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchConfig {
    @Value("${elasticsearch.hostlist}")
    private String hostlist;

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        //解析hostlist的节点配置信息
        String[] hosts = hostlist.split(",");
        //创建HttpHost数组，其中存放es主机和端口配置信息
        HttpHost[] httpHostArray = new HttpHost[hosts.length];
        for(int i=0;i<hosts.length;i++){
            httpHostArray[i] = new HttpHost(hosts[i].split(":")[0],
                    Integer.parseInt(hosts[i].split(":")[1]),"http");
        }
        //创建RestHighClient客户端
        return new RestHighLevelClient(RestClient.builder(httpHostArray));
    }
}
